<?php

namespace catchAdmin\registration\controller;

use app\common\model\Follow;
use app\common\model\PatientInfo;
use app\common\model\PhoneRecord;
use catchAdmin\system\model\AppSetting;
use catcher\CatchResponse;
use catcher\base\CatchRequest;
use catcher\base\CatchController;
use app\common\model\Followtask as FollowtaskModel;
use app\common\model\FollowHistory as FHModel;
use catchAdmin\registration\request\MobileResultRequest;
use catcher\exceptions\FailedException;
use catchAdmin\registration\service\TaskService;
use catchAdmin\registration\request\ModifyResultRequest;
use Ofan\PhoneLocation;
use think\facade\Log;

class Myfollow extends CatchController
{
    protected $followtask;

    public function __construct(FollowtaskModel $followtask)
    {
        $this->followtask = $followtask;
    }

    /**
     * 列表
     *
     * @time 2022年09月21日
     * @param CatchRequest $request
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        $user = request()->user();
        $field = "id,taskname,endtime,status,condition";
        $where = [];
        $custom_dept_id = $request->header('custom-dept-id');

        $dept_id = $user['department_id'];
        if (isset($custom_dept_id) && !empty($custom_dept_id)) {
            $dept_id = (int)$custom_dept_id;
        }

        //type 1 正常计划  2 分娩计划
        if (isset($req['type']) == 2) {
            $where[] = ['creator_dept_id', '=', $dept_id];
            $where[] = ['is_long', '=' , 1];
        }else{
            $where[] = ['is_long', '<>' , 1];
            $where[] = ['follow_staff.user_id', '=', $user['id']];
        }
        if (isset($req['home']) && $req['home'] == 1) {
            $where[] = ['status', '=', 1];

        }
        return CatchResponse::paginate($this->followtask->myFollowData($where, $field));
    }

    /**
     * 统计当前随访人员任务状态
     *
     * @return \think\response\Json
     */
    public function myfollow_status_count(): \think\response\Json
    {
        return CatchResponse::success($this->followtask->countStatus());
    }

    /**
     * 我的随访任务
     * @time 2022年10月13日
     * @return \think\response\Json
     */
    public function my_taskname()
    {
        return CatchResponse::success($this->followtask->getMyTask());
    }

    /**
     * 随访任务对应问卷模板
     * @time 2022年10月18日
     * @return \think\response\Json
     */
    public function get_follow_template(CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success($this->followtask->getTemplate($request->param('task_id')));
    }

    /**
     * 随访任务对应短信模板
     * @time 2022年10月18日
     * @return \think\response\Json
     */
    public function get_follow_sms(CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success($this->followtask->getSms($request->param('task_id')));
    }

    /**
     * 保存电话随访结果
     * @time 2023年02月13日
     * @return \think\response\Json
     */
    public function tel_follow_result(MobileResultRequest $request): \think\response\Json
    {
        $req = $request->param();
        $user = request()->user();
        $userDept = $userInfo->userDept ?? [];
        if ($req['type'] == 1) {
            $ret = (new TaskService())->savePhoneFollowResults($req, $user, $userDept);
        }else{
            $ret = (new TaskService())->saveDoctorFollowResults($req, $user, $userDept);
        }
        return CatchResponse::success($ret);
    }

    /**
     * 来电信息
     * @time 2023年03月01日
     * @return \think\response\Json
     */
    public function incoming_tel_info(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        $id = $req['id'] ?? '';
        $mobile = $req['mobile']?? '';

        $telRecord = [];
        //根据手机号获取患者信息
        try {
            if (!empty($mobile)) {

                if(mb_strlen($mobile) <=8){
                    if (!isset($req['device_code']) || empty($req['device_code'])) {
                        throw new FailedException('设备码不能为空');
                    }
                    $areaCode = (new AppSetting())->where('device_code', $req['device_code'])->field('LocalAreaCode')->find();

                    $mobile = $areaCode['LocalAreaCode'].$mobile;
                }else{
                    if($mobile[0]==0){
                        $mobile =  mb_substr($mobile, 0, 4) . "-" . mb_substr($mobile, 4);
                    }
                }

                $patientInfo = (new PatientInfo())->getOneData([["relationInfo.mobile", "=", $mobile]]);
                $rndData = [
                    'call_time' => date("Y-m-d H:i:s"),
                    'medicalRecordsNo' => $patientInfo['medicalRecordsNo'] ?? "",
                    'patientUUID' => $patientInfo["id"] ?? "",
                    'patientId' => $patientInfo["patientId"] ?? "",
                    'name' => $patientInfo['name'] ?? "",
                    'mobile' => $mobile ?? '',
                    'home_of_call' => (new PhoneLocation())->find($mobile),
                    'call_back_number' => '',
                    'status' => 0,
                    'task_name' => '',
                    'follow_id' => '',
                    'button_type' => 0,
                    'deleted_at' => 0,
                    'task_id'=>''
                ];
                $telRecord = (new PhoneRecord())->create($rndData);
            }

        } catch (\Exception $exception) {
            Log::error("患者来电数据写入失败，失败原因:" . $exception->getMessage());
        }
        $result = (new TaskService())->getIncomingTel($id, $mobile);
        if (!empty($result)) {
            //将记录id追加到result中
            $result["tel_id"] = $telRecord["id"] ?? "";
            if (!empty(trim($mobile)) && (!empty($result["follow_id"]) || !empty($result["taskname"]))) {
                //执行随访记录更新操作
                $telRecord->save([
                    'follow_id' => $result["follow_id"] ?? "",
                    'task_id' => $result["task_id"] ?? "",
                    'task_name' => $result['taskname'] ?? "",
                    'button_type' => 1
                ]);
            }
        }
        return CatchResponse::success($result);
    }

    /**
     * 获取患者随访历史记录
     * @time 2023年03月09日
     * @return \think\response\Json
     */
    public function patien_follow_history(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        if (!array_key_exists('type', $req) || empty($req['type'])) {
            throw new FailedException("缺少type");
        }


        if (!array_key_exists('patientId', $req) || empty($req['patientId'])) {
            throw new FailedException("缺少patientId");
        }

        if (!isset($req['task_id'])) {
            $req['task_id'] = '';
        }

        return CatchResponse::paginate((new FHModel())->getPatientFollowHistory($req['type'], $req['patientId'], $req['task_id']));
    }

    /**
     *  随访路径保存电话结果
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function automaticPushTel(CatchRequest $request): \think\response\Json
    {
        $req = $request->post();
        return CatchResponse::success((new TaskService())->automaticTelResult($req));
    }

    /**
     * 电话随访上一位下一位患者
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function phoneFollowNext(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        $user = request()->user();

//        if (!isset($req['id']) || empty($req['id'])) {
//            throw new FailedException('id不能为空');
//        }
        if (!isset($req['task_id']) || empty($req['task_id'])) {
            throw new FailedException('task_id不能为空');
        }
        if (!isset($req['type']) || empty($req['type'])) {
            throw new FailedException('type不能为空');
        }
        $ret = (new TaskService())->switchToNextPosition($req['task_id'], $user['id'], $req['type'], $req['id']);
        return CatchResponse::success($ret);
    }

    /**
     * 获取随访结果详情
     * @time 2024年01月03日
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function getTelFollowResultDetails(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        $follow_mode = config('dictionary.follow_mode');
        if (!isset($req['id']) || empty($req['id'])) {
            throw new FailedException('随访记录id不能为空');
        }
        $where['id'] = $req['id'];
        $field = 'id,pid,mode,follow_id,pushtime,pushdatetime,result,resultCategory,resultName,resultIsEffective,remarks,health_status,adverse_reaction,staffName,followup_conclusion,recurrence,death,transfer,updated_at,modify_user_name';
        $ret = (new FHModel())->getOneData($where, $field);

        $ret['resultCategory'] = $ret['resultCategory'] ?? '';
        $ret['resultName'] = $ret['resultName'] ?? '';
        $ret['is_effective'] = $ret['resultIsEffective'] ?? '';

        if (isset($ret['mode']) && !empty($ret['mode'])) {
            $ret['mode'] = $follow_mode[$ret['mode']];
        }
        return CatchResponse::success($ret);
    }

    /**
     * 修改随访结果
     * @time 2024年01月03日
     * @param ModifyResultRequest $request
     * @return \think\response\Json
     */
    public function modifyTelFollowResult(ModifyResultRequest $request): \think\response\Json
    {
        $req = $request->param();
        return CatchResponse::success((new TaskService())->modifyFollowResult($req));
    }

    /**
     * 暂存
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function stagingFollow(CatchRequest $request): \think\response\Json
    {
        try {
            $req = $request->param();
            $user = request()->user();

            if (!isset($req['pid']) || empty($req['pid'])) {
                throw new FailedException("pid不能为空");
            }

            $patientData['staging_status'] = 1;
            $patientData['staging_date'] = date("Y-m-d");
            $patientData['staging_operator_id'] = $user['id']??'';
            $patientData['staging_operator_name'] = $user['name']??'';
            $patientData['staging_operator_doctor_code'] = $user['doctor_code']??'';
            $patientData['staging_operator_department_id'] = $user['department_id']??'';
            (new PatientInfo())->saveData($req['pid'], $patientData);

            return CatchResponse::success();
        } catch (\Exception $exception) {
            throw new FailedException($exception->getMessage());
        }
    }

    /**
     * 撤销暂存
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function revokeStagingFollow(CatchRequest $request): \think\response\Json
    {
        try {
            $req = $request->param();

            if (!isset($req['pid']) || empty($req['pid'])) {
                throw new FailedException("pid不能为空");
            }

            $patientData['staging_status'] = 0;
            $patientData['staging_date'] = '';
            $patientData['staging_operator_id'] = '';
            $patientData['staging_operator_name'] = '';
            $patientData['staging_operator_doctor_code'] = '';
            $patientData['staging_operator_department_id'] = '';

            (new PatientInfo())->saveData($req['pid'], $patientData);

            return CatchResponse::success();
        } catch (\Exception $exception) {
            throw new FailedException($exception->getMessage());
        }
    }
    
        /**
     * 问卷患者信息
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function getQuestPatientInfo(CatchRequest $request): \think\response\Json
    {
        $req = $request->param();
        if (!isset($req['follow_id']) || empty($req['follow_id'])) {
            throw new FailedException('follow_id不能为空');
        }
        $followInfo = (new Follow())->where('id', $req['follow_id'])->find();

        $ret = [];
        if ($followInfo['status'] == 2) {
            $ret['name'] = $followInfo['name'];
            $ret['presentTelphone'] = $followInfo['presentTelphone'];
            $ret['outhospitalDate'] = $followInfo['outhospitalDate'];
            $ret['inchargeDoctorName'] = $followInfo['inchargeDoctorName'];
            $ret['time_of_birth'] = $followInfo['time_of_birth'];
            //计算年龄
            $ret['inage'] = '';
            if (!empty($follow['birthdate'])) {
                $ret['inage'] = floor((time() - strtotime($follow['birthdate'])) / 31556926); // 计算年龄
            }
        }else{
            $patientInfo = (new PatientInfo())->where('patientId', $followInfo['patientId'])->field('name,presentTelphone,outList')->find();
            $ret['name'] = $patientInfo['name'];
            $ret['presentTelphone'] = $patientInfo['presentTelphone'];
            $ret['outhospitalDate'] = '';
            $ret['inchargeDoctorName'] = $patientInfo['outList']['attendingDoctorName'];
            $ret['time_of_birth'] = '';
        }
        return CatchResponse::success($ret);
    }
}